import React from "react";
import {
  getLangs,
  setLangs,
  setToken,
  removeToken,
} from "@/utils/localStorage";
import getAssetsFile from "@/utils/pub-use";
import {
  CenterPopup,
  Dialog,
  Image,
  Input,
  Picker,
  Toast,
  Swiper,
} from "antd-mobile";
import { useEffect, useState } from "react";
import Web3 from "web3";
import { useTranslation } from "react-i18next";
import { Account } from "@/common/web3/webMethods.js";
import { useNavigate } from "react-router-dom";
import { getBannerList } from "@/api/module/information";
import {
  BanlanceType,
  checkUser,
  userInc,
  userInfo,
  checkLang,
  changeLang,
} from "@/api/module/user";
import copy from "copy-to-clipboard";
import { useAppDispatch } from "@/hooks/useAppDispatch";
import { fetchUserInfo, fetchConfig } from "@/store/slices/userInfo";
import { useAppSelector } from "@/hooks/useAppSelector";
const HeaderComponent = (props) => {
  const navigate = useNavigate();
  const { t, i18n } = useTranslation();
  const dispatch = useAppDispatch();

  const typeColumns = [
    [
      { label: "中文简体", value: "zh" },
      { label: "English", value: "en" },
    ],
  ];
  const reqCheckLang = async () => {
    const res = await checkLang();
    if (res.code === 0) {
      i18n.changeLanguage(res.data.lang.split("-")[0]);
      setLangs(res.data.lang.split("-")[0]);
    }
  };
  const langs = {
    zh: "zh-cn",
    en: "en-us",
  };
  const reqChangeLang = async (lang: string) => {
    const res = await changeLang(lang);
    if (res.code === 0) {
      i18n.changeLanguage(lang);
      dispatch(fetchUserInfo());
    }
  };
  const [isDarkMode, setIsDarkMode] = useState(true); // 初始为暗黑模式
  const changeStyleColor = () => {
    setIsDarkMode((prevMode) => !prevMode);
    if (!isDarkMode) {
      // 设置为暗黑模式
      document.documentElement.style.setProperty("--background-color", "#000");
    } else {
      // 设置为浅色模式
      document.documentElement.style.setProperty("--background-color", "#fff");
    }
  };
  useEffect(() => {
    reqCheckLang();
  }, []);
  const [pickerVisible, setPickerVisible] = useState(false);
  const [pickerValue, setPickerValue] = useState<(string | null)[]>();
  return (
    <div className="flex justify-between items-center py-2">
      <div className="left">
        <Image
          width={"100px"}
          height={"45.5px"}
          src={getAssetsFile("home/logo.png")}
        />
      </div>
      <div className="right flex items-center nth-child(n-1)">
        {/* <Image
          width={"40px"}
          src={getAssetsFile("home/tips-icon.png")}
          onClick={changeStyleColor}
        /> */}
        <div
          style={{
            margin: "0px 5px",
            borderRadius: "15px",
            border: "1px solid #fff",
            paddingLeft: "5px",
            paddingRight: "5px",
          }}
        >
          <p>
            {props.addressWallet.slice(0, 4)}...{props.addressWallet.slice(-4)}
          </p>
        </div>
        <Image
          onClick={() => setPickerVisible(true)}
          width={"40px"}
          src={getAssetsFile("home/langs-icon.png")}
        />
        <Image
          onClick={() => navigate("/settings")}
          width={"40px"}
          src={getAssetsFile("home/avatar-icon.png")}
        />
      </div>
      <Picker
        cancelText={t("cancel")}
        confirmText={t("confirm")}
        style={{
          // @ts-ignore
          "--adm-color-background": "#242424",
        }}
        className="text-white-1 bg-bg-1"
        columns={typeColumns}
        visible={pickerVisible}
        onClose={() => {
          setPickerVisible(false);
        }}
        value={pickerValue}
        onConfirm={(v, extend) => {
          console.log(v);
          // @ts-ignore
          setPickerValue(v);
          // @ts-ignore
          getLangs() != v[0] && i18n.changeLanguage(v[0]);
          // @ts-ignore
          setLangs(v[0]);
          console.log(v, extend.items);
          reqChangeLang(langs[v[0] as keyof typeof langs]);
        }}
      />
    </div>
  );
};
const AssetsComponent = () => {
  const { t } = useTranslation();
  const userInfo = useAppSelector((state) => state.userInfo.userInfo);
  return (
    <div>
      <div className="flex items-center justify-between asstest mx-2 bg-custom-gradient-1 py-5 px-4 rounded-xl pb-6">
        <div className="left">
          <div className="opacity-50 text-xs">{t("accountTotalValue")}</div>
          <div className="font-bold text-2xl mt-1">${userInfo.total_value}</div>
        </div>
        <div className="right">
          <div className="opacity-50 text-xs">{t("YesterdayEarnings")}</div>
          <div className="font-bold text-2xl mt-1">
            {userInfo.profit_yesterday >= 0 ? "+" : "-"}$
            {userInfo.profit_yesterday}
          </div>
        </div>
      </div>
      <div className="value py-3 px-4 text-black-1 bg-custom-gradient-2 rounded-xl relative -top-4">
        <div className="match flex items-center justify-between">
          <div className="left">
            <div className="title opacity-50 text-xs">
              {t("matchingQuantity")}
            </div>
            <div className="text-3xl font-bold">
              {userInfo.c2c_data.amount_today}
            </div>
          </div>
          <div className="right">
            <div className="text-3xl font-bold">${userInfo.c2c_data.price}</div>
            {/* <div className="text-font-1 font-bold text-lg">+2.12%</div> */}
          </div>
        </div>
        <div className="time flex items-center justify-between mt-4">
          <div className="left text-xs">
            {t("updateTime")}
            {userInfo.c2c_data.last_matched_time}
          </div>
          {/* <div
            className="right px-2 rounded-full text-sm bg-black-5 text-white-1 flex py-1 items-center"
            style={{ fontSize: '75%' }}
          >
            BEP20 {t('smartContracts')}9
            <div className="border border-solid border-font-2 font-bold rounded-full flex ml-2">
              <RightOutline color="#FEC85D" fontSize={12} />
            </div>
          </div> */}
        </div>
      </div>
    </div>
  );
};
const BannerComponent = () => {
  return (
    <div>
      <Image src={getAssetsFile("home/banner.png")} />
    </div>
  );
};
const BannerComponentOne = (props) => {
  return (
    <div style={{ marginBottom: "15px" }}>
      <Swiper loop autoplay>
        {props.bannerList.map((banner, index) => (
          <Swiper.Item key={index}>
            <Image src={banner.path} alt={`Banner ${index}`} />
          </Swiper.Item>
        ))}
      </Swiper>
    </div>
  );
};

const TransactionComponent = () => {
  const navigate = useNavigate();
  const { t } = useTranslation();

  const list = [
    {
      image: getAssetsFile("home/recharge.png"),
      title: "recharge",
      path: "/recharge",
    },
    {
      image: getAssetsFile("home/withdraw.png"),
      title: "withdraw",
      path: "/withdraw",
    },
    {
      image: getAssetsFile("home/transfer.png"),
      title: "transfer",
      path: "/transfer",
    },
    {
      image: getAssetsFile("home/exchange.png"),
      title: "exchange",
      path: "/exchange",
    },
  ];
  return (
    <div className="my-6 flex justify-between items-center text-center">
      {list.map((item) => {
        return (
          <div onClick={() => navigate(item.path)} key={item.title}>
            <Image width={56} src={item.image} />
            <div className="mt-2 text-sm">{t(item.title)}</div>
          </div>
        );
      })}
    </div>
  );
};

interface tabbarType {
  title: string;
  image: string;
  key1: keyof Awaited<ReturnType<typeof userInfo>>["data"];
  key2?: string;
}
const OperateComponent = () => {
  const navigate = useNavigate();
  const userInfo = useAppSelector((state) => state.userInfo.userInfo);
  const { t } = useTranslation();
  const tabbarList: Array<tabbarType> = [
    {
      title: "gubenjin",
      image: getAssetsFile("home/first.png"),
      key1: "RWA",
      name: "GPB",
    },
    {
      title: "SimuDou",
      image: getAssetsFile("home/second.png"),
      key1: "RWB",
      name: "GBJ",
    },
    {
      title: "USDT",
      image: getAssetsFile("home/third.png"),
      key1: "USDT",
      name: "USDT",
    },
    {
      title: "CashBeans",
      image: getAssetsFile("home/fourth.png"),
      key1: "XJD",
      name: "XJB",
    },
    {
      title: "ActivateBeans",
      image: getAssetsFile("home/fifth.png"),
      key1: "JHD",
      name: "JHB",
    },
    {
      title: "RegisterBeans",
      image: getAssetsFile("home/sixth.png"),
      key1: "ZCD",
      name: "ZCB",
    },
    {
      title: "BeidouBean",
      image: getAssetsFile("home/seventh.png"),
      key1: "STD",
      name: "STF",
    },
    {
      title: "BillionBeans",
      image: getAssetsFile("home/eighth.png"),
      key1: "FTD",
      name: "FTB",
    },
  ];
  return (
    <div className="mt-4">
      <div
        className="title font-semibold"
        style={{
          fontSize: "1.07rem",
        }}
      >
        {t("myAssets")}
      </div>
      <div className="tabbar flex flex-wrap justify-between mt-2">
        {tabbarList.map((item, index) => {
          const handleClick = () => {
            if (item.title === "SimuDou") {
              // 假设你使用的是 Next.js 路由
              navigate("/buy");
            }
          };
          return (
            <div
              key={index}
              className="tabbar-item w-[48%] bg-bg-1 mb-4 rounded-lg p-2"
              onClick={handleClick} // 添加点击事件
            >
              <div className="flex items-center">
                <Image width={"48px"} src={item.image} />
                <div className="ml-2">{item.key1}</div>
              </div>
              <div className="mt-1 text-lg font-bold">
                $
                {userInfo[item.name] &&
                  (userInfo[item.name] as BanlanceType).balance}
              </div>
              {item.key2 && (
                // eslint-disable-next-line react/react-in-jsx-scope
                <div className="text-xs mt-1 opacity-50">{t(item.key2)}</div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
};

export default function Home() {
  const { t } = useTranslation();
  const [visible, setVisible] = useState(false);
  const [value, setValue] = useState("");
  const [addressWallet, setAddressWallet] = useState("");
  const dispatch = useAppDispatch();
  const [bannerList, setBannerList] = useState([]);
  // 初始化web3
  const init = async () => {
    removeToken();
    try {
      /**
       * 初始化
       */
      // const checkEtherenum = await check()
      // if(!checkEtherenum) {
      // 	return
      // }
      const web3 = new Web3((window as any).ethereum);
      // console.log(web3);
      // return
      // if (window.location.hash) {
      //   const url = window.location.hash.slice(3).includes('code')
      //     ? window.location.hash.slice(3)
      //     : location.search;
      // const urlParams = new URLSearchParams(url);
      // const code = urlParams.get('code');
      // const regex = /\d+/g;
      // const numbers = code?.match(regex);
      // invitationCode.value = numbers?.[0] || ''
      // console.log(invitationCode.value)
      // }
      await Account.init(web3);
      await Account.addCToken("USDT");
      setAddressWallet(Account.address);
      let address = Account.address;
      const checkRes = await checkUser(address);
      // setAddressWallet(address);
      // return;
      if (checkRes.code == 404) {
        const searchParams = new URLSearchParams(location.href.split("?")[1]);
        console.log(searchParams);
        if (searchParams.get("code")) {
          addUser(searchParams.get("code") as string, address);
          return false;
        }
        setVisible(true);
        return;
      } else {
        setToken(checkRes.data._token);
        dispatch(fetchUserInfo());
        dispatch(fetchConfig());
        fetchBannerList();
      }
      return;
    } catch (e) {
      switch ((e as any).code) {
        case -32000:
          // alert(`${env[CHAIN_NAME_SYMBOL].name}的JSON-RPC接口异常`);
          break;
        default:
      }
      console.log("🚀 ~ file: home.react:245 ~ init ~ e:", e);
    }
  };
  // 注册新用户
  const addUser = async (value: string, address: string) => {
    // uni.removeStorageSync('userToken')
    let params: Parameters<typeof userInc>[0] = {
      invite_code: value,
      address: address,
    };
    console.log(params);
    // 注册新用户
    await userInc(params)!.then((res) => {
      console.log(res);
      if (res.code === 0) {
        console.log(res.data);
        setVisible(false);
        setToken(res.data._token);
        dispatch(fetchUserInfo());
        dispatch(fetchConfig());
        fetchBannerList();

        // Dialog.alert({
        //   title: t("saveGoogleKey"),
        //   content: res.data.google_secret,
        //   confirmText: <div className="text-bg-16">{t("copy")}</div>,
        //   onConfirm: () => {
        //     copy(res.data.google_secret);
        //     Toast.show({
        //       content: t("copySuccess"),
        //     });
        //   },
        // });
      } else {
        Toast.show({
          content: res.msg,
          afterClose: () => {
            setVisible(true);
          },
        });
        // popupContent.isShow = false
      }
    });
  };

  const fetchBannerList = async () => {
    try {
      const res = await getBannerList();
      if (res.code === 0) {
        setBannerList(res.data);
      }
    } catch (err) {
      console.error(err);
    }
  };
  useEffect(() => {
    // eslint-disable-next-line @typescript-eslint/no-unused-expressions
    setAddressWallet(Account.address);
    !Account.address
      ? init()
      : (() => {
          console.log("1");
          dispatch(fetchUserInfo());
          dispatch(fetchConfig());
          fetchBannerList();
        })();
  }, []);
  return (
    <div className="text-white-1 px-3 pb-28">
      <HeaderComponent addressWallet={addressWallet} />
      <AssetsComponent />
      <BannerComponentOne bannerList={bannerList} />
      <BannerComponent />
      <TransactionComponent />
      <OperateComponent />
      <CenterPopup
        visible={visible}
        onMaskClick={() => {
          setVisible(false);
        }}
      >
        <div className="bg-bg-1 text-center p-4">
          <div className="title font-bold text-lg">{t("invite")}</div>
          <div className="my-4">
            <Input
              maxLength={6}
              value={value}
              onChange={(val) => {
                setValue(val);
              }}
              className="bg-bg-18"
              style={{
                "--text-align": "center",
                "--color": "#fff",
              }}
              placeholder={t("enter")}
              clearable
            />
          </div>
          <div className="btn flex justify-between items-center">
            <div
              onClick={() => setVisible(false)}
              className="flex-1 border rounded-full py-1"
            >
              {t("cancel")}
            </div>
            <div
              onClick={() => addUser(value, Account.address)}
              className="bg-bg-16 flex-1 ml-4 rounded-full py-1 border border-bg-16"
            >
              {t("confirm")}
            </div>
          </div>
        </div>
      </CenterPopup>
    </div>
  );
}
